<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import CustomNavBar from './component/NavBar.vue'
import { getBannerList, getHomeCategoryApi, getHomeHotApi } from '@/services/home'
import { ref } from 'vue'
import CategoryPanel from './component/CategoryPanel.vue'
import HotPanel from './component/HotPanel.vue'
import pageSkeleton from './pageSkeleton.vue'
import type { BannerItem, HomeCategory, HomeHot } from '@/types/home'
import type { XtxGuessInstance } from '@/components/comonents'
import { useGuessList } from '@/composables'

const isLoading = ref(false)

// 获取轮播数据
const bannerList = ref<BannerItem[]>([])
const getBanner = async () => {
  let res = await getBannerList(1)
  bannerList.value = res.result
}

// 获取前台分类
const Category = ref<HomeCategory[]>([])
const getHomeCategoryData = async () => {
  let res = await getHomeCategoryApi()
  Category.value = res.result
}

// 获取热门推荐
const hot = ref<HomeHot[]>([])
const getHomeHotData = async () => {
  let res = await getHomeHotApi()
  hot.value = res.result
}

// 调用猜你喜欢组合式函数
const { guessRef, scrolltolower } = useGuessList()

// 滚动触底
const scrollLower: UniHelper.ScrollViewOnScrolltolower = (val) => {
  scrolltolower()
}
// 下拉刷新
const refreshOk = ref(false) // 刷新ok
const refresherrefresh: UniHelper.ScrollViewOnRefresherrefresh = async () => {
  refreshOk.value = true //控制下拉状态
  await Promise.all([getBanner(), getHomeCategoryData(), getHomeHotData()])
  // 重置列表条件
  guessRef.value?.resetData()
  await guessRef.value?.getMore()
  refreshOk.value = false
}

// 页面加载
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getBanner(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})
</script>

<template>
  <!-- 导航栏 -->
  <CustomNavBar />
  <!-- 使用scroll-view  控制滚动区域以及下拉刷新 -->
  <scroll-view
    @scrolltolower="scrollLower"
    class="scroll"
    scroll-y
    refresher-enabled
    @refresherrefresh="refresherrefresh"
    :refresher-triggered="refreshOk"
  >
    <pageSkeleton v-if="isLoading" />

    <template v-else>
      <!-- 轮播图 -->
      <XtxSwiper :list="bannerList" />
      <!-- 分类组件 -->
      <CategoryPanel :list="Category" />
      <!-- 热门推荐 -->
      <HotPanel :hot="hot" />
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  width: 100%;
  height: 100%;
  background-color: #f7f7f7;
  display: flex;
  flex-direction: column;

  .scroll {
    flex: 1;
  }
}
</style>
